import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { RedisService } from "@liaoliaots/nestjs-redis";
import { RedisNamespace } from "@/common/config/config.interface";
import { LoggerService } from '@/common/logger/logger.service';
import { AdminModel } from '@/module/admin/admin.model';

@Injectable()
export class AdminAuthGuard implements CanActivate {
  constructor(
    private readonly redisService: RedisService,
    private readonly loggerService: LoggerService,
  ) {}

  static authExpireSecond = 7 * 24 * 60 * 60; // 一周

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.token ?? request.query.__token;
    if (!token) {
      throw new UnauthorizedException();
    }
    const adminLoginRedisClient = this.redisService.getClient(
      RedisNamespace.admin_login,
    );
    const adminStr = await adminLoginRedisClient.get(token);
    if (!adminStr) {
      throw new UnauthorizedException();
    }
    const admin: AdminModel = JSON.parse(adminStr);
    adminLoginRedisClient.expire(token, AdminAuthGuard.authExpireSecond); // 异步刷新session时间
    request.admin = admin;
    return true;
  }
}

